import React from 'react';
import { DeviceTypeItem, ConnectState } from '@/models/connect';
import { connect } from 'dva';
import _ from 'lodash';
import styles from './index.css';
import { DeviceInfo, DynamicFormType } from '@/models/device';

interface OtherFormProps {
  dynamicForms: DynamicFormType[];
  deviceInfo: DeviceInfo;
}

const formartDynamicFiledsValue: (
  item: DynamicFormType,
  value: number | string | boolean,
) => any = (item, value) => {
  if (item.type === 'singleSelect') {
    const o = _.find(item.singleOption, v => v.itemValue == value);
    return o && o.itemName;
  }
  return value;
};

const OtherForm: React.FC<OtherFormProps> = ({ dynamicForms, deviceInfo }) => {
  console.log(dynamicForms, deviceInfo,25)
  return (
    <div className={styles.ulcontainer}>
      <ul>
        {_.map(dynamicForms, (item: DynamicFormType) => {
          const data = JSON.parse(deviceInfo.extendedField || JSON.stringify({}));
          const value = data[item.fieldName];

          return (
            <li>
              <div className={styles.liitem1}>{item.label}</div>
              <div className={styles.liitem2}>{formartDynamicFiledsValue(item, value)}</div>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

export default connect(({ device }: ConnectState) => {
  const { deviceTypeNoOptions, selectDeviceTypeNo } = device;
  const typeOptionItem: DeviceTypeItem | undefined = _.find(
    deviceTypeNoOptions,
    item => item.deviceTypeNo == selectDeviceTypeNo,
  );

  const dynamicForms: DynamicFormType = JSON.parse(
    (typeOptionItem && typeOptionItem.extendedField) || '[]',
  );

  return {
    dynamicForms,
  };
})(OtherForm);
